package com.wyp.demo.gallery;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.AttributeSet;
import android.widget.ImageSwitcher;
import android.widget.ImageView;

public class MyImageSwitcher extends ImageSwitcher {
	public MyImageSwitcher(Context context) {
        super(context);
    }
    
	public MyImageSwitcher(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

    public void setImageFile(String filePath)
    {
        ImageView image = (ImageView)this.getNextView();
        BitmapFactory.Options opts = new BitmapFactory.Options();  
		opts.inJustDecodeBounds = true;  
		BitmapFactory.decodeFile(filePath, opts);  
		  
		opts.inSampleSize = computeSampleSize(opts, -1, 1200*1200);  
		opts.inJustDecodeBounds = false;  
		
		Bitmap nbm = BitmapFactory.decodeFile(filePath,opts);
		image.setImageBitmap(nbm);
        showNext();
        System.gc();
    }
	private int computeInitialSampleSize(BitmapFactory.Options options,int minSideLength, int maxNumOfPixels) {  
	    double w = options.outWidth;  
	    double h = options.outHeight;  
	  
	    int lowerBound = (maxNumOfPixels == -1) ? 1 :  
	            (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));  
	    int upperBound = (minSideLength == -1) ? 128 :  
	            (int) Math.min(Math.floor(w / minSideLength),  
	            Math.floor(h / minSideLength));  
	  
	    if (upperBound < lowerBound) {  
	        // return the larger one when there is no overlapping zone.   
	        return lowerBound;  
	    }  
	  
	    if ((maxNumOfPixels == -1) &&  
	            (minSideLength == -1)) {  
	        return 1;  
	    } else if (minSideLength == -1) {  
	        return lowerBound;  
	    } else {  
	        return upperBound;  
	    }  
	} 
	
	public int computeSampleSize(BitmapFactory.Options options,  
	        int minSideLength, int maxNumOfPixels) {  
	    int initialSize = computeInitialSampleSize(options, minSideLength,maxNumOfPixels);  
	  
	    int roundedSize;  
	    if (initialSize <= 8 ) {  
	        roundedSize = 1;  
	        while (roundedSize < initialSize) {  
	            roundedSize <<= 1;  
	        }  
	    } else {  
	        roundedSize = (initialSize + 7) / 8 * 8;  
	    }  
	  
	    return roundedSize;  
	} 
}
